package redis

import (
	"cart_srv/cart"
	"errors"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"strconv"
)

// 获取库存
func GetGoodsStock(goodsId int) int64 {

	//LLEN 是 Redis 命令之一，用于获取列表（list）的长度，即列表中元素的数量
	key := "goods_stock:goods_id_" + strconv.Itoa(goodsId)
	//fmt.Println(key)
	return Rdb.LLen(key).Val()
}

// 添加购物车
func AddCart(userId, goodsId int, cart map[string]interface{}) error {

	key := "cart:user_id_" + strconv.Itoa(userId) + ":goods_id_" + strconv.Itoa(goodsId)
	fmt.Println("Redis key:", key)
	fmt.Println("Cart data:", cart)
	// 确保 cart 包含正确的字段
	if len(cart) == 0 {
		return errors.New("购物车数据为空")
	}
	return Rdb.HMSet(key, cart).Err()
}

func GetCartGoodsIsExists(userId, goodsId int) bool {
	key := "cart:user_id_" + strconv.Itoa(userId) + ":goods_id_" + strconv.Itoa(goodsId)
	//fmt.Println(key)
	result, err := Rdb.Exists(key).Result()
	fmt.Println(result)
	if err != nil {
		logx.Error("检查购物车商品是否存在时发生错误:", err)
		return false
	}
	return result == 1

}
func UpdateCartNum(userId, goodsId, num int) error {
	key := "cart:user_id_" + strconv.Itoa(userId) + ":goods_id_" + strconv.Itoa(goodsId)
	return Rdb.HIncrBy(key, "quantity", int64(num)).Err()
}

// 购物车列表
func CartList(userId int) (cartList []*cart.CartList, count int, amount float64, err error) {
	key := "cart:user_id_" + strconv.Itoa(userId) + ":*"
	count = 0
	amount = 0.00

	val, _ := Rdb.Keys(key).Result()
	fmt.Println(val)
	if len(val) == 0 {
		return nil, 0, 0, errors.New("购物车没有商品")
	}
	for _, v := range val {
		result, _ := Rdb.HGetAll(v).Result()
		//fmt.Println(result)

		goodsId, _ := strconv.Atoi(result["goodsId"])
		quantity, _ := strconv.Atoi(result["quantity"])
		goodsName := result["goodsName"]

		goodsPrice, _ := strconv.ParseFloat(result["goodsPrice"], 64)

		// 添加到购物车列表
		cartList = append(cartList, &cart.CartList{
			UserId:     int32(userId),
			GoodsId:    int32(goodsId),
			GoodsName:  goodsName,
			GoodsPrice: float32(goodsPrice),
			Quantity:   int32(quantity),
		})
		// 累加数量和总金额
		count += quantity
		amount += goodsPrice * float64(quantity)
		fmt.Println(count)
		fmt.Println(amount)
	}
	return cartList, count, amount, nil
}
func CleanCart(userId int) error {
	key := "cart:user_id_" + strconv.Itoa(userId) + ":*"
	keys := Rdb.Keys(key).Val()
	fmt.Println(keys)
	for _, v := range keys {
		Rdb.Del(v)
	}
	return nil
}
func DelCart(userId, goodsId int) error {
	key := "cart:user_id_" + strconv.Itoa(userId) + ":goods_id_" + strconv.Itoa(goodsId)
	keys, _ := Rdb.Keys(key).Result()
	Rdb.Del(keys...)
	return nil
}
func CartSum(userId int) (count int, amount float64, err error) {

	count = 0
	amount = 0.00

	key := "cart:user_id_" + strconv.Itoa(userId) + ":*"
	// 累加数量和总金额
	result, err := Rdb.Keys(key).Result()
	if err != nil {
		return 0, 0, err
	}
	for _, v := range result {
		re, _ := Rdb.HGetAll(v).Result()
		quantity, _ := strconv.Atoi(re["quantity"])
		goodsPrice, _ := strconv.ParseFloat(re["goodsPrice"], 64)
		fmt.Println(quantity)
		fmt.Println(goodsPrice)
		count += quantity
		amount += goodsPrice * float64(quantity)
		fmt.Println(count)
		fmt.Println(amount)
	}
	return count, amount, nil
}
